package com.MediaVaultTest;

import java.io.IOException;
import java.util.Collection;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.util.List;

public class multiDelete extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<String> stringKeys = Arrays.asList(req.getParameterValues("formatKey"));
		for(String stringKey: stringKeys){
			Key key = KeyFactory.stringToKey(stringKey);
			//Get the format
		    Format format = pm.getObjectById(Format.class, key);
		    //delete the file
	        blobstoreService.delete(format.getBlobKey());
	        //clean up the data structures
	        Media media = format.getMedia();
	        if(media.getCover()!=null){
	        	blobstoreService.delete(media.getCover());
	        }
	        UserStore userStore = media.getUserStore();
	        userStore.setmbStorage(userStore.getmbStorage()-format.getSize());
	        String stringMedia = media.getKeyForTrans();
	        media.removeFormat(format);
	        pm.deletePersistent(format);
	        //if thats the last format
	        if(media.getNumFormats()==0){
	        	userStore.removeMediaFile(media);
	        	pm.deletePersistent(media);
	        }
		}
        pm.close();
        res.sendRedirect("/");
    }
}